<template>
  <div class="home-container">
    <!-- 轮播图 -->
    <el-carousel height="400px" class="banner-carousel">
      <el-carousel-item v-for="(video, index) in topVideos" :key="index">
        <div class="carousel-item">
          <img 
            :src="video.video_cover || '/placeholder.svg?size=1200x400'" 
            :alt="video.video_title"
            class="carousel-image"
          >
          <div class="carousel-info">
            <h3>{{ video.video_title }}</h3>
            <p class="video-intro">{{ video.video_intro }}</p>
            <div class="video-stats">
              <span class="stat-item"><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
              <span class="stat-item"><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
              <span class="stat-item"><el-icon><View /></el-icon> {{ video.view_count }}</span>
            </div>
            <el-button type="primary" @click="goToVideoDetail(video.video_id)">立即观看</el-button>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 左侧：分类视频 -->
      <div class="main-content">
        <div v-for="type in videoTypes" :key="type.type_id" class="video-category">
          <div class="category-header">
            <h2>{{ type.type_name }}</h2>
            <el-button type="text" @click="goToCategory(type.type_id)">查看更多 ></el-button>
          </div>
          <div class="video-grid">
            <el-card 
              v-for="video in getVideosByType(type.type_id)" 
              :key="video.video_id"
              class="video-card"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="video-cover">
                <img 
                  :src="video.video_cover || '/placeholder.svg?size=300x180'" 
                  :alt="video.video_title"
                  class="cover-image"
                >
                <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count }}</span>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.video_title }}</h3>
                <div class="video-meta">
                  <span class="author">{{ getUserName(video.user_id) }}</span>
                  <div class="video-stats-small">
                    <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 右侧：最新视频 -->
      <div class="sidebar">
        <div class="sidebar-section">
          <h3 class="sidebar-title">最新上传</h3>
          <div class="latest-video-list">
            <div 
              v-for="(video, index) in latestVideos" 
              :key="video.video_id"
              class="latest-video-item"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="rank-number">{{ index + 1 }}</div>
              <img 
                :src="video.video_cover || '/placeholder.svg?size=120x68'" 
                :alt="video.video_title"
                class="latest-video-cover"
              >
              <div class="latest-video-info">
                <h4 class="latest-video-title">{{ video.video_title }}</h4>
                <div class="latest-video-meta">
                  <span>{{ getUserName(video.user_id) }}</span>
                  <span>{{ formatTime(video.video_time) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="sidebar-section">
          <h3 class="sidebar-title">热门推荐</h3>
          <div class="hot-video-list">
            <div 
              v-for="(video, index) in popularVideos.slice(0, 10)" 
              :key="video.video_id"
              class="hot-video-item"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="rank-number hot-rank" :class="getRankClass(index)">{{ index + 1 }}</div>
              <h4 class="hot-video-title">{{ video.video_title }}</h4>
              <div class="hot-video-stats">
                <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                <span><el-icon><View /></el-icon> {{ video.view_count }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useVideoStore } from '../store/videoStore'
import { useUserStore } from '../store/userStore'
import { StarFilled, View, ChatDotRound } from '@element-plus/icons-vue'
import { ElCarousel, ElCarouselItem, ElButton, ElCard } from 'element-plus'

export default {
  name: 'HomeView',
  components: {
    ElCarousel,
    ElCarouselItem,
    ElButton,
    ElCard,
    StarFilled,
    View,
    ChatDotRound
  },
  setup() {
    const router = useRouter()
    const videoStore = useVideoStore()
    const userStore = useUserStore()
    const commentsMap = ref({})

    onMounted(async () => {
      await initData()
    })

    const initData = async () => {
      await Promise.all([
        videoStore.fetchVideos(),
        videoStore.fetchVideoTypes(),
        loadComments()
      ])
    }

    const loadComments = async () => {
      try {
        const comments = await fetch('http://localhost:3000/comments')
        const data = await comments.json()
        // 统计每个视频的评论数
        data.forEach(comment => {
          if (!commentsMap.value[comment.video_id]) {
            commentsMap.value[comment.video_id] = 0
          }
          commentsMap.value[comment.video_id]++
        })
      } catch (error) {
        console.error('加载评论失败:', error)
      }
    }

    // 计算属性
    const topVideos = computed(() => videoStore.popularVideos.slice(0, 6))
    const latestVideos = computed(() => videoStore.latestVideos.slice(0, 6))
    const popularVideos = computed(() => videoStore.popularVideos)
    const videoTypes = computed(() => videoStore.videoTypes)

    // 方法
    const getVideosByType = (typeId) => {
      return videoStore.getVideosByType(typeId).slice(0, 4)
    }

    const getCommentCount = (videoId) => {
      return commentsMap.value[videoId] || 0
    }

    const getUserName = (userId) => {
      // 简化处理，实际应该从用户store获取
      const userMap = {
        1: '张三',
        2: '李四',
        3: '王五',
        4: '赵六',
        5: '测试用户1',
        6: '测试用户2'
      }
      return userMap[userId] || '未知用户'
    }

    const formatTime = (timeString) => {
      const date = new Date(timeString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    const getRankClass = (index) => {
      if (index === 0) return 'rank-1'
      if (index === 1) return 'rank-2'
      if (index === 2) return 'rank-3'
      return ''
    }

    const goToVideoDetail = (videoId) => {
      router.push(`/video/${videoId}`)
    }

    const goToCategory = (typeId) => {
      router.push(`/category/${typeId}`)
    }

    return {
      topVideos,
      latestVideos,
      popularVideos,
      videoTypes,
      getVideosByType,
      getCommentCount,
      getUserName,
      formatTime,
      getRankClass,
      goToVideoDetail,
      goToCategory
    }
  }
}
</script>

<style scoped>
.home-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: var(--bg-primary);
}

.banner-carousel {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.carousel-item {
  position: relative;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(to top, rgba(0,0,0,0.9), transparent);
  color: white;
}

.carousel-info h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: white;
}

.video-intro {
  margin: 0 0 15px 0;
  font-size: 14px;
  opacity: 0.9;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-stats {
  margin-bottom: 15px;
}

.stat-item {
  margin-right: 20px;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.content-wrapper {
  display: flex;
  gap: 30px;
}

.main-content {
  flex: 1;
}

.sidebar {
  width: 300px;
  flex-shrink: 0;
}

.video-category {
  margin-bottom: 40px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #00b42a;
}

.category-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--text-primary);
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.video-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  background-color: var(--bg-card) !important;
  border-color: var(--border-color) !important;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.video-cover {
  position: relative;
  margin-bottom: 10px;
}

.cover-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
}

.view-count {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.video-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: var(--text-secondary);
}

.author {
  flex: 1;
}

.video-stats-small {
  display: flex;
  gap: 10px;
}

.video-stats-small span {
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
  color: var(--text-secondary);
}

.sidebar-section {
  background: var(--bg-card);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  border: 1px solid var(--border-color);
}

.sidebar-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: var(--text-primary);
  border-left: 4px solid #00b42a;
  padding-left: 10px;
}

.latest-video-item {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.latest-video-item:hover {
  background-color: var(--bg-secondary);
}

.rank-number {
  width: 20px;
  height: 20px;
  background: var(--bg-secondary);
  color: var(--text-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
  flex-shrink: 0;
  margin-top: 2px;
}

.latest-video-cover {
  width: 120px;
  height: 68px;
  object-fit: cover;
  border-radius: 4px;
  flex-shrink: 0;
}

.latest-video-info {
  flex: 1;
  min-width: 0;
}

.latest-video-title {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.latest-video-meta {
  font-size: 12px;
  color: var(--text-disabled);
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.hot-rank.rank-1 {
  background: #ff6b6b;
  color: white;
}

.hot-rank.rank-2 {
  background: #ffa502;
  color: white;
}

.hot-rank.rank-3 {
  background: #ffd700;
  color: white;
}

.hot-video-item {
  margin-bottom: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.hot-video-item:hover {
  background-color: var(--bg-secondary);
}

.hot-video-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.hot-video-title {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-video-stats {
  font-size: 12px;
  color: var(--text-disabled);
  display: flex;
  gap: 10px;
  margin-left: 30px;
}

.hot-video-stats span {
  display: flex;
  align-items: center;
  gap: 3px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
  }
  
  .video-grid {
    grid-template-columns: 1fr;
  }
  
  .carousel-info h3 {
    font-size: 20px;
  }
  
  .video-intro {
    display: none;
  }
}
</style>